import argparse
import m3u8dl
import re
import os
import logging

# 设置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


def validate_url(url):
    # 简单的URL格式校验
    regex = re.compile(
        r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"
    )
    return regex.match(url) is not None


def validate_name(name):
    # 确保文件名不包含非法字符
    if any(char in name for char in '/\\:.*?'):
        return False
    return True


def download_m3u8(url, name, proxy=None, download_dir='./m3u8dlDownloads'):
    if not os.path.exists(download_dir):
        os.makedirs(download_dir)
    try:
        md = m3u8dl.M3u8Downloader(lambda mp4path: logging.info('下载完成: ' + mp4path))
        if proxy:
            # 设置代理
            proxies = {
                'http': proxy,
                'https': proxy
            }
            md.proxies = proxies
        md.download_m3u8(url, name, download_dir)
    except Exception as e:
        logging.error(f"下载过程中发生错误: {e}")


def main():
    # 使用argparse处理命令行参数
    parser = argparse.ArgumentParser(description='m3u8下载器')
    parser.add_argument('--url', type=str, help='m3u8地址')
    parser.add_argument('--name', type=str, help='下载文件名')
    parser.add_argument('--proxy', type=str, help='代理(optional)')
    args = parser.parse_args()

    if not validate_url(args.url):
        logging.error('请输入合法的URL')
        return

    if not validate_name(args.name):
        logging.error('文件名包含非法字符')
        return

    download_m3u8(args.url, args.name, proxy=args.proxy)


if __name__ == '__main__':
    main()
